package btracker;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

/**
 *  LoginSequence procedure : Allows user to Access their personal information
 *  from a directory
 * 
 *  LoginGUI procedure: Contains GUI for Login Interface
 *
 *  ButtonHandler: Handles all button pressing actions
 *
 *  @version : Feb 25 2010
 *
 * @author Sammy Guergachi
 */
public class Login {

    ///////////////////////////
    //Declare Class Variables//
    ///////////////////////////
    static JButton btnLogIn;
    static JButton btnCancel;
    static JButton btnNewPassword;
    static JPasswordField txtPassWord;
    static JTextField txtUserName;
    static JLabel lblUserName;
    static JLabel lblPassWord;
    static JLabel lblTitle;
    static JFrame loginFrame;
    static JPanel pnlTextField;

    public static void LoginGUI() throws ClassNotFoundException, InterruptedException {


        //--------------------------pnlTitle///////////START////////////
        //Adds a title to the LoginSequence window

        ///create Title Panel
        JPanel pnlTitle = new JPanel();
        //Setup the Title
        lblTitle = new JLabel("Please Login With Your User Name And Password");
        pnlTitle.add(BorderLayout.CENTER, lblTitle);

        //--------------------------pnlTitle\\\\\\\\\\\END\\\\\\\\\\\\\

        //******************************************************************

        //--------------------------pnlButtons///////////START////////////
        ///Panel containing buttons for Log In Window

        //Create Panel and Set Layout
        JPanel pnlButtons = new JPanel();
        pnlButtons.setLayout(new GridLayout(0, 3, 10, 10));

        //Declare New Buttons Commponent
        btnLogIn = new JButton("Log In"); // Log In Button
        btnCancel = new JButton("Cancel"); // Cancel Button
        btnNewPassword = new JButton("New User"); //New User Button

        ////Create new Button Action Handlers
        ButtonHandler onClick = new ButtonHandler();

        btnLogIn.addActionListener(onClick);
        btnLogIn.setActionCommand("login");

        btnCancel.addActionListener(onClick);
        btnCancel.setActionCommand("cancel");

        btnNewPassword.addActionListener(onClick);
        btnNewPassword.setActionCommand("newpassword");

        // Add Buttons to panel
        pnlButtons.add(btnNewPassword);
        pnlButtons.add(btnLogIn);
        pnlButtons.add(btnCancel);

        //--------------------------pnlButtons\\\\\\\\\\\END\\\\\\\\\\\\\

        //******************************************************************

        //--------------------------pnlTextField///////////START////////////
        //Contains all text and lables for Log In window

        ///Create panel for User Inputs
        pnlTextField = new JPanel();


        //Declare new commponents
        txtPassWord = new JPasswordField();
        txtUserName = new JTextField();
        lblUserName = new JLabel("User Name");
        lblPassWord = new JLabel("Password");


        //Add to the Panel Containg textFields

        pnlTextField.setLayout(new GridLayout(2, 2, 10, 10));

        pnlTextField.add(lblUserName);
        pnlTextField.add(txtUserName);
        pnlTextField.add(lblPassWord);
        pnlTextField.add(txtPassWord);

        //--------------------------pnlTextField\\\\\\\\\\\END\\\\\\\\\\\\\

        //******************************************************************

        //--------------------------pnlNorth///////////START////////////

        /// North Panel (pnlTitle + pnlTextField)
        JPanel pnlNorth = new JPanel();
        pnlNorth.setLayout(new GridLayout(2, 0, 10, 3));
        pnlNorth.add(BorderLayout.NORTH, pnlTitle);
        pnlNorth.add(BorderLayout.CENTER, pnlTextField);

        //--------------------------pnlNorth\\\\\\\\\\\END\\\\\\\\\\\\\

        //******************************************************************

        //--------------------------loginFrame///////////START////////////

        ///Set Up Window
        loginFrame = new JFrame();

        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        loginFrame.setTitle("Log In ~ BTracker  V 0.31 ");
        loginFrame.setVisible(true);
        loginFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("bTlogo.png"));
        loginFrame.setSize(450, 200);
        loginFrame.add(BorderLayout.SOUTH, pnlButtons);
        loginFrame.add(BorderLayout.NORTH, pnlNorth);
        loginFrame.setResizable(false);
        loginFrame.setLocationRelativeTo(null);
        loginFrame.repaint();
        //--------------------------loginFrame\\\\\\\\\\\END\\\\\\\\\\\\\

    }
    ///Declare Class Variables//
    static String username;
    static String password;
    static String dir;
    static boolean userExist;

    public static void LoginSequence() throws FileNotFoundException, IOException, InterruptedException {

        //Create new Stream I/O readers
        FileReader read = new FileReader("directory.ini");
        Scanner reader1 = new Scanner(read);

        System.out.println("\n ----------------------------------");
        System.out.println("LOGIN IN WITH USERNAME: " + Login.txtUserName.getText());
        System.out.println("LOGIN IN WITH PASSWORD: " + Login.convertPassword(Login.txtPassWord.getPassword()));



        //Linear Search used here to find directory of specified username


        boolean flag = false;
        //While there is still text in the file,  continue
        while (reader1.hasNextLine() == true) {

            //If user name input equals username in file then get username and stop
            if (reader1.nextLine().equalsIgnoreCase(Login.txtUserName.getText())) {
                dir = reader1.nextLine(); //Get the users directory
                System.out.println("\n user match confirmed...");
                System.out.println("Getting dirrectory Confirmation.... \n");
                flag = true;
                break; // get out of loop

            } else { // skip line if no match

                System.out.println("no match in line");
            }
        }





        if (reader1.hasNextLine() == false && flag == false) { //if reach end of file then user match is not possible
            //Give error
            JOptionPane.showMessageDialog(Login.loginFrame, "Unable to login user name does not exist");
            userExist = false; // User Dose not Exist
        } else {// If not then user match was accomplished
            //check if
            if (Login.txtUserName.getText().equalsIgnoreCase("") || convertPassword(Login.txtPassWord.getPassword()).equalsIgnoreCase("")) {
                JOptionPane.showMessageDialog(Login.loginFrame, "Unable to login please check username or password");
                userExist = false;
            } else {


                userExist = true; // User does exist

                // read from UserData in user folder
                FileReader UserDataFile = null;
                try {
                    UserDataFile = new FileReader(dir + "\\UserData.data");
                    System.out.println("dirrectory Confirmation Success.... \n");

                } catch (FileNotFoundException ex) {
                    System.out.println("dirrectory Confirmation Denied. \n");
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
                // Create new reader
                BufferedReader reader = new BufferedReader(UserDataFile);
                //Start reading UserData file
                username = reader.readLine();
                String key = reader.readLine();
                String pass = reader.readLine();
                reader.close();
                password = Crypt.decrypt(pass, key);


            }
        }
    }

    private static class ButtonHandler implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();




            ///-----------------------------------LOGIN BUTTON PRESS ACTION


            if (command.equals("login")) { //check if login button pressed
                try {
                    try {
                        Login.LoginSequence(); // try to login
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }


                System.out.println("confirming username...");
                if (userExist == true) { //Check if user name is found

                    System.out.println("username confirmed...");

                    //check if password in user file is the same as inputed password
                    System.out.println("confirming password...");
                    if (password.equalsIgnoreCase(Login.convertPassword(Login.txtPassWord.getPassword()))) {
                        // show user login is in effect
                        Login.pnlTextField.removeAll();
                        Login.lblTitle.setFont(new Font("Arial", 0, 30));
                        Login.lblTitle.setText("LOGING IN");

                        try {

                            

                           Loader.gui(); // calls timer to allow GUI for MainWindow to load
                            
                            System.out.println("password confirmed.");
                            
                            
                            Login.loginFrame.dispose();


                        } catch (InterruptedException ex) {
                            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else { // Error if password not correct
                        JOptionPane.showMessageDialog(Login.loginFrame, "Unable to login please check username or password");
                        System.out.println("password confirmation denied...");
                    }

                } else { //Error If user name can not be found in the local file
                    System.out.println("user name confermation denied.");
                    System.out.println("password confirmation denied...");

                }



                ///-----------------------------------CANCEL BUTTON PRESS ACTION


            } else if (command.equals("cancel")) { // Check if cancel button was pressed
                if (btnCancel.getText().equalsIgnoreCase("Cancel")) {
                    System.exit(0);

                } else { //minimizes the login UI to Normal size


                    ///Shrink Frame
                    for (int i = 300; i >= 200; i = i - 50) {
                        try {
                            Thread.sleep(90);
                        } catch (InterruptedException ex) {
                            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        Login.loginFrame.setSize(450, i);

                    }

                    //Remove all text fields

                    Login.pnlTextField.removeAll();


                    Login.pnlTextField.setLayout(new GridLayout(2, 2, 0, 10));
                    //re-add text fields
                    Login.pnlTextField.repaint();
                    Login.pnlTextField.add(Login.lblUserName);
                    Login.pnlTextField.add(Login.txtUserName);
                    Login.pnlTextField.add(Login.lblPassWord);
                    Login.pnlTextField.add(Login.txtPassWord);



                    ///Change text back to normal
                    Login.btnLogIn.setEnabled(true);
                    Login.btnNewPassword.setText("New User");
                    Login.lblPassWord.setText("Password");
                    Login.btnCancel.setText("Back");
                    Login.lblUserName.setText("User Name");
                    Login.lblTitle.setText("Please Login With Your User Name And Password");
                }
                //rename button to cancel
                Login.btnCancel.setText("Cancel");
            } else if (command.equals("newpassword")) {
                try {
                    try {
                        try {
                            NewUser.newUserGUI();
                        } catch (IOException ex) {
                            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                        }

                    } catch (InstantiationException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ClassNotFoundException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IllegalAccessException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnsupportedLookAndFeelException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    }

                } catch (InterruptedException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    
    public static String convertPassword(char[] Password) {
        // Declare variables
        String strRet = new String("");

        // Go through each character
        for (int i = 0; i < Password.length; i++) {
            strRet += Password[i];
        }

        return strRet;
    }
}
